package com.example.coreshopapp.ui;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.example.coreshopapp.MainActivity;
import com.example.coreshopapp.R;
import com.example.coreshopapp.adapter.CategoryAdapter;
import com.example.coreshopapp.adapter.GoodsAdapter;
import com.example.coreshopapp.app.Constants;
import com.example.coreshopapp.base.BaseActivity;
import com.example.coreshopapp.bean.GoodsCategoryData;
import com.example.coreshopapp.bean.GoodsData;
import com.example.coreshopapp.bean.GoodsReq;
import com.example.coreshopapp.bean.MemberData;
import com.example.coreshopapp.bean.MemberGoodsReq;
import com.example.coreshopapp.databinding.ActivityClassifyBinding;
import com.example.coreshopapp.fragment.BottomShopCartFragment;
import com.example.coreshopapp.net.BaseApplication;
import com.example.coreshopapp.task.GetMemberGoodsTask;
import com.example.coreshopapp.task.GoodsCategoryTask;
import com.example.coreshopapp.task.GoodsTask;
import com.example.coreshopapp.utils.FormDataUtils;
import com.example.coreshopapp.utils.LoadingUtils;
import com.example.coreshopapp.utils.OrderingUtils;
import com.example.coreshopapp.utils.SnowIdUtils;
import com.example.coreshopapp.utils.TimeUtils;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.journeyapps.barcodescanner.CaptureActivity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import bean.OrderBean;
import bean.OrderItemBean;
import cn.hutool.db.sql.Order;
import dao.DaoSession;
import dao.OrderBeanDao;
import dao.OrderItemBeanDao;

public class ClassifyActivity extends BaseActivity {
    private Window window;
    private ActivityClassifyBinding binding;
    private RequestManager glideRequests;
    private Animation enterAnim;
    private Runnable debounceRunnable; // 防抖函数
    private Handler debounceRunnableHandler = new Handler(Looper.getMainLooper()); // 使用handler方法
    // dao start
    private DaoSession daoSession;
    private OrderBeanDao orderBeanDao; // 订单购物车数据，支付提交后清空数据
    private OrderItemBeanDao orderItemBeanDao; // 订单购物车数据，支付提交后清空数据

    private BottomShopCartFragment bottomShopCartFragment; // 购物车弹框
    // dao end
    private GoodsAdapter goodsAdapter;
    private CategoryAdapter goodsCategoryAdapter;
    private List<GoodsData> goodsList = new ArrayList<>();
    private List<GoodsCategoryData> goodsCategoryList = new ArrayList<>();
    private OrderBean orderInfo; // 当前订单
    private String orderId;
    private List<OrderItemBean> orderItemList = new ArrayList<>(); // 购物车商品数据
    private GoodsReq goodsReq = new GoodsReq(true, 1, 9999, 0, "", ""); // 只需要修改category即可
    private List<GoodsData> memberGoods;
    private Boolean isScanCode = false; // 用于判断是否是扫码商品
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            binding.goodsList.setVisibility(View.GONE);
            binding.goodsNone.setVisibility(View.VISIBLE);
            binding.goodsLoading.setVisibility(View.GONE);
            glideRequests.clear(binding.loadingImg);
            switch (msg.what) {
                case 9900:
                    binding.goodsList.scrollToPosition(0);
                    goodsList = JSON.parseArray(msg.obj.toString(), GoodsData.class);
                    goodsAdapter.updateData(goodsList, orderItemList);
                    if (goodsList.size() > 0) {
                        binding.goodsList.setVisibility(View.VISIBLE);
                        binding.goodsNone.setVisibility(View.GONE);
                    }
                    if ( isScanCode && goodsList.size() > 0) {
                        // 判断是扫码直接加入购物车
                        addShopCart(goodsList.get(0));
                    }
                    break;
                case 9901:
                    isScanCode = false;
                    Toast.makeText(ClassifyActivity.this, "获取失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    isScanCode = false;
                    Toast.makeText(ClassifyActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    isScanCode = false;
                    gotoActivityFinish(LoginActivity.class);
                    Toast.makeText(ClassifyActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
            super.handleMessage(msg);
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler goodsHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
            switch (msg.what) {
                case 9900:
                    memberGoods = JSON.parseArray(msg.obj.toString(),GoodsData.class);
                    changeShopCartPrice();
                    break;
                case 9901:
                    Toast.makeText(ClassifyActivity.this, "获取失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(ClassifyActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    gotoActivityFinish(LoginActivity.class);
                    Toast.makeText(ClassifyActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
            super.handleMessage(msg);
        }
    };

    // 判断是否有会员有调用会员接口，将价格重置
    @SuppressLint("HandlerLeak")
    private Handler categoryHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) { // 处理传递回来数据
            LoadingUtils.hideProgressDialog();
            switch (msg.what) {
                case 9900:
                    goodsCategoryList = JSON.parseArray(msg.obj.toString(), GoodsCategoryData.class);
                    goodsCategoryAdapter.updateGoodsCategory(goodsCategoryList);
                    goodsReq.setGoodsCategoryId(goodsCategoryList.get(0).getId());
                    getGoodsList();
                    break;
                case 9901:
                    Toast.makeText(ClassifyActivity.this, "获取失败：" + msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case 9902:
                    Toast.makeText(ClassifyActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
                    break;
                case 9904:
                    gotoActivityFinish(LoginActivity.class);
                    Toast.makeText(ClassifyActivity.this, msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
            super.handleMessage(msg);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify);
        binding = ActivityClassifyBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        hideTopBar();
        initView();
        getQueryBuilder();
        viewClick();
//        getRequest();
//        orderBeanDao.deleteAll();
//        orderItemBeanDao.deleteAll();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        Log.d("onPostResume: ","show");
    }
    //    private void getStorage() {
//        SharedPreferences share = getSharedPreferences("dangbanInfo", MODE_PRIVATE);
//        classBillNo = share.getString("classBillNo", "");
//        Constants.AppConstVars.classBillNo = classBillNo;
//
//    }

    private void initView() {
        enterAnim = AnimationUtils.loadAnimation(this, R.anim.push_bottom_in); // 弹出样式
        window = getWindow();
        binding.searchEt.clearFocus();

        goodsAdapter = new GoodsAdapter(goodsList, orderItemList);
        goodsAdapter.setOnItemAddClickListener(goodsItemAddClick);
        goodsAdapter.setOnItemMinusClickListener(goodsItemMinusClick);
        goodsAdapter.setOnItemNumClickListener(goodsItemNumClick);
        binding.goodsList.setAdapter(goodsAdapter);

        goodsCategoryAdapter = new CategoryAdapter(goodsCategoryList);
        goodsCategoryAdapter.setOnItemClickListener(categoryItemClick);
        binding.classifyList.setAdapter(goodsCategoryAdapter);

        daoSession = BaseApplication.getInstance().getDaoSession(ClassifyActivity.this);
        orderBeanDao = daoSession.getOrderBeanDao();
        orderItemBeanDao = daoSession.getOrderItemBeanDao();

        bottomShopCartFragment = new BottomShopCartFragment(); // 创建购物车弹窗
        bottomShopCartFragment.setAddClick(cartAddQuantity);
        bottomShopCartFragment.setMinusClick(cartMinusQuantity);
        bottomShopCartFragment.setNumClick(cartNumClick);
        bottomShopCartFragment.setOnDelete(cartDeleteClick);

        binding.selectUserClick.setVisibility(Constants.AppConstVars.classBillNo.equals("") ? View.VISIBLE : View.GONE);

        MemberData memberInfo = Constants.AppConstVars.MemberInfo;
        binding.memberInfo.setText(memberInfo != null ?"会员：" + memberInfo.getNickName() : "会员");
//        binding.memberInfo.setVisibility(memberInfo != null ?View.VISIBLE : View.GONE);
    }

    private void getQueryBuilder() {
        // 查询数据库
        getOrderListDao();
        getMemberGoods(); // 拿到购物车数据后调用
    }

    private void getRequest() {
        // 调用接口
        // 1. xml将分类隐藏
        // 2.不需要分类修改直接调用商品
//        getGoodsCategoryList();
        getGoodsList();
    }

    private void getGoodsList() {
        glideRequests = Glide.with(this);
        glideRequests.asGif()
                .load("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201510%2F22%2F20151022160243_rUX4n.thumb.1000_0.gif&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1750835999&t=15a024773f32be44dc48aca2a8f4fe63").placeholder(R.mipmap.loading) // 占位符图片
                .error(R.mipmap.loading) // 错误符图片
                .fitCenter() // 正确用法
                .into(binding.loadingImg);
        binding.goodsList.setVisibility(View.GONE);
        binding.goodsNone.setVisibility(View.GONE);
        binding.goodsLoading.setVisibility(View.VISIBLE);
        MemberData memberInfo = Constants.AppConstVars.MemberInfo;
        if(memberInfo!= null) {
            goodsReq.setMemberId(memberInfo.id);
        } else {
            goodsReq.setMemberId(0);
        }
        // 3.获取商品时将分类id设置为0
        goodsReq.setGoodsCategoryId(0);
        GoodsTask goodsTask = new GoodsTask(FormDataUtils.buildFormData(goodsReq));
        goodsTask.setOutHandler(mHandler);
        goodsTask.execute();
    }

    private void getGoodsCategoryList() {
        LoadingUtils.showProgressDialog(getActivity(), "温馨提示", "加载中，请稍后");
        GoodsCategoryTask goodsCategoryTask = new GoodsCategoryTask();
        goodsCategoryTask.setOutHandler(categoryHandler);
        goodsCategoryTask.execute();
    }

    private void viewClick() {
        binding.goPayOrder.setOnClickListener(view -> {
            // 去订单 如果没有当班人或者下单数据则不让下单
            if (Constants.AppConstVars.classBillNo.equals("")) {
                showtoast(this, "请选择当班人");
                return;
            }
            if (orderItemList == null ||  orderItemList.size() < 1) {
                showtoast(this, "请选择商品");
                return;
            }
            gotoActivity(OrderPayActivity.class);
        });

        binding.selectUserClick.setOnClickListener(view -> {
            // 选择会员
        });
        binding.searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                // 防抖
                if (debounceRunnable != null) {
                    debounceRunnableHandler.removeCallbacks(debounceRunnable);
                }
                debounceRunnableHandler.postDelayed(debounceRunnable = () -> {
                    String searchName = binding.searchEt.getText().toString().trim().toString();
                    goodsReq.setBarcode("");
//                    goodsReq.setGoodsCategoryId(0);
                    if (searchName.equals("")) {
                        goodsReq.setName("");
                    } else {
                        goodsReq.setName(searchName);
                    }
                    getGoodsList();
                }, 800);

            }
        });
        // 扫码
        binding.scanCode.setOnClickListener(view -> {
            scan();
        });
        binding.shopCartLy.setOnClickListener(view -> {
            // 打开购物车
            if (orderItemList == null || orderItemList.size() < 1) {
                Toast.makeText(this, "购物车暂无数据", Toast.LENGTH_SHORT).show();
                return;
            }
            Bundle bundle = new Bundle();
            String s = JSON.toJSONString(orderItemList);
            bundle.putString("cartList", s);
            bottomShopCartFragment.setArguments(bundle);
            bottomShopCartFragment.show(getSupportFragmentManager(), bottomShopCartFragment.getTag());

            bottomShopCartFragment.setClearClick(() -> {
                new AlertDialog.Builder(this)
                        .setTitle("温馨提示")
                        .setMessage("确认删除吗？")
                        .setPositiveButton("确认", (dialogInterface, i) -> {
                            bottomShopCartFragment.dismiss();
                            orderItemBeanDao.deleteAll();
                            getOrderItemListDao(orderId);
                            calculateTotalPrice();
                        })
                        .setNegativeButton("取消", null)
                        .create()
                        .show();
            });
        });
        binding.selectUserClick.setOnClickListener(view -> {
            // 选择当班人
            Bundle bundle = new Bundle();
            bundle.putString("dangban","dangban");
            gotoActivity(MainActivity.class,bundle);
        });
        // 刷新界面
        binding.btnRestart.setOnClickListener(view -> {
            restart();
        });
        binding.memberInfo.setOnClickListener(view -> {
            gotoActivity(MemberActivity.class);
        });
    }

    /**
     * 扫码方法
     */
    private void scan() {
        IntentIntegrator integrator = new IntentIntegrator(this);
        // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
        integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
        // 关键：使用自定义的竖屏Activity
        integrator.setCaptureActivity(CaptureActActivity.class);
        integrator.setPrompt("扫描条码");
        integrator.setOrientationLocked(true); // 保持锁定（此时会遵循竖屏设置）
        integrator.setCameraId(0);
        integrator.setBeepEnabled(true);
        integrator.setBarcodeImageEnabled(true);
        integrator.initiateScan();
    }

    /**
     * 扫码结果事件
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "扫码取消！", Toast.LENGTH_LONG).show();
            } else {
                Log.d("扫描成功，条码值: ", result.getContents());
                binding.goodsList.scrollToPosition(0);
                goodsReq.setGoodsCategoryId(0);
                goodsReq.setName("");
                goodsReq.setBarcode(result.getContents());
                goodsCategoryAdapter.setCurrentIndex(0);
                getGoodsList();
                isScanCode = true;
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    CategoryAdapter.OnItemClickListener categoryItemClick = position -> {
        binding.goodsList.scrollToPosition(0);
        goodsReq.setGoodsCategoryId(goodsCategoryList.get(position).getId());
        goodsReq.setName("");
        goodsReq.setBarcode("");
//        binding.searchEt.setText("");
        goodsCategoryAdapter.setCurrentIndex(position);
        getGoodsList();
    };

    //    获取购物车数据
    private void getOrderListDao() {
        List<OrderBean> list = orderBeanDao.queryBuilder()
                .where(OrderBeanDao.Properties.Isdel.notEq(true),
                        OrderBeanDao.Properties.StoreId.eq(Constants.AppConstVars.sysUser.getStoreId())
                        )
                .list();
        if (list.size() > 0) {
            orderInfo = list.get(0);
            this.orderId = list.get(0).getOrderId();
            getOrderItemListDao(list.get(0).getOrderId());
        } else {
            // 没有订单
            orderInfo = null;
            orderItemList = null;
        }
    }

    private void getOrderItemListDao(String orderId) {
        // 获取购物车商品数据
        orderItemList = orderItemBeanDao.queryBuilder()
                .where(OrderItemBeanDao.Properties.OrderId.eq(orderId))
                .list();
        calculateTotalPrice();
        goodsAdapter.updateData(goodsList, orderItemList);
    }

    GoodsAdapter.OnItemMinusClickListener goodsItemMinusClick = (item, orderItem) -> {
        // 商品数量减
        if (orderItem.getNums() > 1) {
            OrderItemBean load = orderItemBeanDao.load(orderItem.getId());
            load.setNums(load.getNums() - 1);
            load.setAmount(OrderingUtils.toFixed(load.getNums() *(load.getPromotionPrice() > 0? load.getPromotionPrice():load.getPrice())));
            orderItemBeanDao.update(load);
        } else {
            orderItemBeanDao.deleteByKey(orderItem.getId());
        }
        getOrderItemListDao(orderId);
    };

    // 数量点击事件
    GoodsAdapter.OnItemNumClickListener goodsItemNumClick = (item,e) -> {
        editDialog(e,false);
    };

    public void editDialog(OrderItemBean e,Boolean isBottom) {
        EditText editText = new EditText(getActivity());
        editText.setHint("请输入数量");
        editText.setText(e.getNums() +"");
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, // 宽度填满父容器
                LinearLayout.LayoutParams.WRAP_CONTENT  // 高度根据内容自适应
        );
//        editText.setInputType(InputType.TYPE_CLASS_NUMBER |
//                InputType.TYPE_NUMBER_FLAG_DECIMAL | 带小数
//                InputType.TYPE_NUMBER_FLAG_SIGNED); 带负数

        editText.setLayoutParams(params);
        // 设置边距
        LinearLayout layout = new LinearLayout(getActivity());
        layout.setPadding(50, 30, 50, 30);
        layout.addView(editText);
        // 创建弹窗
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("请输入商品数量")
                .setView(layout)
                .setPositiveButton("确定", (dialog, which) -> {
                    String input = editText.getText().toString();
                    // 处理输入内容
                    if( input.equals("")||  input.equals("0")) {
                        orderItemBeanDao.deleteByKey(e.getId());
                    } else {
                        OrderItemBean load = orderItemBeanDao.load(e.getId());
                        load.setNums(Integer.parseInt(input));
                        load.setAmount(OrderingUtils.toFixed(load.getNums() * (load.getPromotionPrice() > 0? load.getPromotionPrice():load.getPrice())));
                        orderItemBeanDao.update(load);
                    }
                    getOrderItemListDao(orderId);
                    if(isBottom) {
                    bottomShopCartFragment.update(orderItemList);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    GoodsAdapter.OnItemAddClickListener goodsItemAddClick = item -> {
        // 商品数量加
        addShopCart(item);
    };

    public void addShopCart (GoodsData item) {

        if (orderInfo == null) {
            // 添加订单
            this.orderId = SnowIdUtils.getSnowIdStatic().toString();
            OrderBean orderBean = new OrderBean();
            orderBean.setOrderId(orderId);
            orderBean.setConfirmStatus(0);
            orderBean.setIp("192.168.1.1");
            orderBean.setCostFreight(0.0);
            orderBean.setGoodsAmount(item.getAmount());
            orderBean.setCreateTime(TimeUtils.getCurrentTime());
            orderBean.setCouponDiscountAmount(item.getAmount());
            orderBean.setGoodsDiscountAmount(item.getAmount());
            orderBean.setIsdel(false);
            orderBean.setIsComment(false);
            orderBean.setLogisticsId(0);
            orderBean.setWeight(0.0);
            orderBean.setUserId(Constants.AppConstVars.sysUser.getId());
            orderBean.setStoreId(Constants.AppConstVars.sysUser.getStoreId()); // 根据实际 storeId 设置
            orderBean.setStatus(2);
            orderBean.setSource(666);
            orderBean.setLogisticsName("");
            orderBean.setMark("APP订单");
            orderBean.setOrderType(99);
            orderBean.setSellerId(0);
            orderBean.setOrderAmount(item.getAmount());
            orderBean.setPayedAmount(item.getAmount());
            orderBean.setOrderDiscountAmount(item.getAmount());
            orderBean.setObjectId(0);
            orderBean.setPaymentCode(""); // 根据你的支付方式设置
            orderBean.setPayStatus(2);
            orderBean.setPaymentTime("");
            orderBean.setConfirmTime("");
            orderBean.setReceiptType(0);
            orderBean.setClassBillNo(Constants.AppConstVars.classBillNo);
            orderBean.setShipStatus(6);
            orderBeanDao.insert(orderBean);
            setterOrderItem(item);
        } else {
            // 直接将当前数据添加进购物车
            OrderItemBean loadItem = new OrderItemBean();
            boolean exists = orderItemList.stream()
                    .anyMatch(ele -> {
                        if (ele.getId() == item.getId()) {
                            loadItem.setId(ele.getId());
                            return true;
                        }
                        return false;
                    });
            if (exists) {
                // 有相同数据
                OrderItemBean load = orderItemBeanDao.load(loadItem.getId());
                load.setNums(load.getNums() + 1);
//                load.setPrice(OrderingUtils.toFixed(item.getPrice()));
                load.setAmount(OrderingUtils.toFixed(
                                (load.getPromotionPrice() > 0? load.getPromotionPrice():load.getPrice()) * load.getNums()
                        )
                );
                load.setUpdateTime(TimeUtils.getCurrentTime());
                orderItemBeanDao.update(load);
            } else {
                setterOrderItem(item);
            }
        }
        getOrderListDao();
        getOrderItemListDao(this.orderId);
//        goodsAdapter.updateData(goodsList, orderItemList);
    }

    public void setterOrderItem(GoodsData goods) {
        OrderItemBean item = new OrderItemBean();
        item.setId(Long.parseLong(goods.getId() + ""));
        item.setProductId(goods.getId());
        item.setOrderId(orderId);
        item.setGoodsId(goods.getGoodsId());
        item.setProductId(item.getProductId());
        item.setSn(goods.getSn());
        item.setBn(goods.getBn());
        item.setUnit(goods.getUnit());
        item.setName(goods.getName());
        item.setPrice(goods.getPrice());
        item.setCostprice(goods.getCostprice());
        item.setMktprice(goods.getPrice());
        item.setImageUrl("");
        item.setNums(1);
        item.setPromotionPrice(goods.getPromotionPrice());
        // 修改
        item.setAmount(OrderingUtils.toFixed((item.getPromotionPrice() >0 ?item.getPromotionPrice() : item.getPrice()) * item.getNums()));
        item.setPromotionAmount(item.getPromotionAmount());
        item.setPromotionList(item.getPromotionList()); // 或者 item.setPromotionList("[]");
        item.setWeight(0);
        item.setSendNums(0);
//        item.setAddon(null); // 或者 item.setAddon("{}");
        item.setCreateTime(TimeUtils.getCurrentTime());
        item.setUpdateTime(TimeUtils.getCurrentTime()); // 或者实际时间字符串
        item.setPk_material1(goods.getPk_material1());
        item.setBar_code(goods.getBar_code());
        orderItemBeanDao.insert(item);
    }


    private BigDecimal quantityMaster = new BigDecimal(0);
    private BigDecimal sumAmount = new BigDecimal(0);

    private void calculateTotalPrice() {
        quantityMaster = quantityMaster.subtract(quantityMaster);
        sumAmount = sumAmount.subtract(sumAmount);
        orderItemList.forEach(item -> {
            quantityMaster = quantityMaster.add(BigDecimal.valueOf(item.getNums()));
            sumAmount = sumAmount.add(BigDecimal.valueOf(item.getAmount()));
        });
        int num = OrderingUtils.calculateNum(quantityMaster);
        OrderBean load = orderBeanDao.load(orderId);
        load.setGoodsAmount(OrderingUtils.toFixedTwo(sumAmount));
        load.setSumQuantity(num);
        orderBeanDao.update(load);
        binding.cartNumber.setText("购物车(" + num + ")");
        binding.foodPriceTv.setText("￥" + sumAmount + "");
    }

    // 购物车添加数量事件
    BottomShopCartFragment.SetOnAddClickListener cartAddQuantity = list -> {
        getOrderItemListDao(orderId);
        calculateTotalPrice();
    };
    // 购物车数量减
    BottomShopCartFragment.SetOnMinusClickListener cartMinusQuantity = list -> {
        if (list.size() < 1) {
            bottomShopCartFragment.dismiss();
        }
        getOrderItemListDao(orderId);
        calculateTotalPrice();
    };
    BottomShopCartFragment.SetOnDeleteClickListener cartDeleteClick = list -> {
        if (list.size() < 1) {
            bottomShopCartFragment.dismiss();
        }
        getOrderItemListDao(orderId);
        calculateTotalPrice();
    };

    // 购物车数量点击事件
    BottomShopCartFragment.SetOnNumClickListener cartNumClick = orderItem -> {
        editDialog(orderItem,true);
    };

    // 获取会员购物车数据
    private void getMemberGoods() {
        if(orderItemList == null) return;
        LoadingUtils.showProgressDialog(ClassifyActivity.this,"温馨提示","加载中，请稍后");
        ArrayList<Integer> objects = new ArrayList<>();
        for (OrderItemBean item:orderItemList) {
            objects.add(item.getProductId());
        }
        MemberData memberInfo = Constants.AppConstVars.MemberInfo;
        MemberGoodsReq memberGoodsReq = new MemberGoodsReq(objects,  memberInfo != null ?memberInfo.id : 0);
        GetMemberGoodsTask getMemberGoodsTask = new GetMemberGoodsTask();
        getMemberGoodsTask.setOutHandler(goodsHandler);
        getMemberGoodsTask.execute(memberGoodsReq);
    }
    private void changeShopCartPrice() {
        // 修改全部价格，并且修改总的哪一项价格
        orderItemList.forEach(item->{
            memberGoods.forEach(ele->{
                if (item.getProductId() == ele.getId()) {
                    OrderItemBean load = orderItemBeanDao.load(item.getId());
                    load.setPromotionPrice(ele.getPromotionPrice()> 0 ? ele.getPromotionPrice() : ele.getPrice());
                    load.setAmount(OrderingUtils.toFixed(load.getNums() *(ele.getPromotionPrice() > 0? ele.getPromotionPrice():ele.getPrice())));
                    orderItemBeanDao.update(load);
                }
            });
            getOrderItemListDao(orderId);
            calculateTotalPrice();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d( "onDestroy: ","48488");
//        if (binding.loadingImg != null) {
//        glideRequests.clear(binding.loadingImg);
//        }
        binding = null;
//        if(bottomShopCartFragment != null) {
//            bottomShopCartFragment.dismiss();
//        }
    }
    public void goMain(View view) {
        gotoActivity(MainActivity.class);
    }
}